import React, { useState, useEffect } from 'react';
import { View, Text, Image } from '@tarojs/components';
import './index.less';

export type ToastType = 'success' | 'fail' | 'error' | 'wait' | '';

export interface ToastOptions {
  text: string;
  type?: ToastType; // 传了才显示图标
  duration?: number; // 秒，默认 3
}

let globalShow: ((opts: ToastOptions) => void) | null = null;

export function showToast(
  text: string,
  type?: ToastType,
  duration: number = 3
) {
  globalShow && globalShow({ text, type, duration });
}

export const StatusToast: React.FC = () => {
  const [opts, setOpts] = useState<ToastOptions | null>(null);

  useEffect(() => {
    globalShow = setOpts;
    return () => {
      globalShow = null;
    };
  }, []);

  useEffect(() => {
    if (opts) {
      const t = (opts.duration || 3) * 1000;
      const timer = setTimeout(() => setOpts(null), t);
      return () => clearTimeout(timer);
    }
  }, [opts]);

  if (!opts) return null;

  const { text, type } = opts;
  const isIconMode = !!type;

  // 图标映射（require 后由 webpack 输出 URL）
  const iconMap: Record<NonNullable<ToastType>, string> = {
    success: 'https://file.linkcook.cn/image/wineMiniProgram/home/success.png',
    fail: 'https://file.linkcook.cn/image/wineMiniProgram/home/fail.png',
    error: 'https://file.linkcook.cn/image/wineMiniProgram/home/error.png',
    wait: 'https://file.linkcook.cn/image/wineMiniProgram/home/wait.png',
    '': '',
  };
  const iconSrc = type ? iconMap[type] : '';

  return (
    <View className="status-toast-overlay">
      <View className={isIconMode ? 'box-icon-mode' : 'box-text-mode'}>
        {isIconMode && (
          <Image src={iconSrc} className="status-toast-icon" mode="widthFix" />
        )}
        <Text className={isIconMode ? 'status-toast-text' : 'text-only'}>
          {text}
        </Text>
      </View>
    </View>
  );
};
